﻿using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.Text;

namespace AllInOnePluginBL.Helpers
{
    public class ImageCreator
    {

        public Bitmap CreateImageAndWriteText(List<string> lines)
        {
            var objBmpImage = new Bitmap(250, 450);

            // Create the Font object for the image text drawing.
            var objFont = new Font("Arial", 20, FontStyle.Bold, GraphicsUnit.Pixel);

            // Create a graphics object to measure the text's width and height.
            //var objGraphics = Graphics.FromImage(objBmpImage);

            //// This is where the bitmap size is determined.
            //var intWidth = (int)objGraphics.MeasureString(sImageText, objFont).Width;
            //var intHeight = (int)objGraphics.MeasureString(sImageText, objFont).Height;

            ////// Create the bmpImage again with the correct size for the text and font.
            //objBmpImage = new Bitmap(objBmpImage, new Size(intWidth, intHeight));

            // Add the colors to the new bitmap.
            var objGraphics = Graphics.FromImage(objBmpImage);

            var strFormat = new StringFormat
                                {
                                    Alignment = StringAlignment.Far,
                                    LineAlignment = StringAlignment.Near,
                                };
            // Set Background color
            objGraphics.Clear(Color.White);
            objGraphics.SmoothingMode = SmoothingMode.AntiAlias;
            objGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;

            var builder = new StringBuilder();
            foreach (var line in lines)
            {
                builder.AppendLine(line);
            }

            objGraphics.DrawString(
            builder.ToString(),
            objFont,
            new SolidBrush(Color.FromArgb(102, 102, 102)),
            new RectangleF(0, 0, 250, 450),
            strFormat);

            objGraphics.Flush();

            return (objBmpImage);
        }

        public void WriteToImage(string imageLocation, string textToWrite)
        {
            var firstLocation = new PointF(10f, 10f);

            var bitmap = (Bitmap)Image.FromFile(imageLocation); //load the image file

            using (var graphics = Graphics.FromImage(bitmap))
            {
                using (var arialFont = new Font("Arial", 10))
                {
                    graphics.DrawString(textToWrite, arialFont, Brushes.Blue, firstLocation);
                }
            }

            bitmap.Save(imageLocation); //save the image file
        }
    }
}
